package com.cat.dataStructure02;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/power-grid-maintenance/description/
 * @create 2025/10/31 16:54
 * @since JDK17
 */

class Solution88 {
    public int[] processQueries(int c, int[][] connections, int[][] queries) {
        List<Integer>[] g = new List[c + 1];
        Arrays.setAll(g, o -> new ArrayList<>());
        // 1. 建图
        for (var e : connections) {
            int x = e[0], y = e[1];
            g[x].add(y);
            g[y].add(x);
        }
        int n = queries.length, k = 0;
        int[] belong = new int[c + 1], offline = new int[c + 1], mx = new int[c + 1];
        Arrays.fill(belong, -1);
        Arrays.fill(offline, Integer.MAX_VALUE);
        Arrays.fill(mx, Integer.MAX_VALUE);
        for (int i = 1, cc = 0; i <= c; i++) { // 记录每一个连通块中的所有电站
            if (belong[i] < 0) {
                dfs(i, g, cc++, belong);
            }
        }

        for (int i = queries.length - 1; i >= 0; i--) {
            var q = queries[i];
            int x = q[0], y = q[1];
            if (x == 2) { // 记录最早的离线时间
                offline[y] = i;
            } else {
                k++;
            }
        }

        for (int i = 1; i <= c; i++) {
            if (offline[i] != Integer.MAX_VALUE) { // 已经离线了
                continue;
            }
            int j = belong[i];
            mx[j] = Math.min(mx[j], i); // 找到每一个块中的最小值
        }
        int[] ans = new int[k];
        for (int i = queries.length - 1; i >= 0; i--) {
            var q = queries[i];
            int x = q[0], y = q[1];
            if (x == 2) {
                if (offline[y] == i) { // 在此之前处于在线的状态
                    mx[belong[y]] = Math.min(mx[belong[y]], y);
                }
            } else {
                k--;
                if (i < offline[y]) { // 在线
                    ans[k] = y;
                } else if (mx[belong[y]] != Integer.MAX_VALUE) {
                    ans[k] = mx[belong[y]];
                } else {
                    ans[k] = -1;
                }
            }
        }

        return ans;
    }

    void dfs(int x, List<Integer>[] g, int f, int[] belong) {
        belong[x] = f;
        for (int y : g[x]) {
            if (belong[y] < 0) {
                dfs(y, g, f, belong);
            }
        }
    }
}
